//
//  XGL_MessageViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/13.
//

import UIKit
import MJRefresh

class XGL_MessageViewController: UIViewController,CustomNavgationBar{
    
    var tableView: UITableView!
    var conversationDatas: [XGL_MessageChatData] = []
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshBackNormalFooter()
    var pageIndex: NSInteger = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
//        self.reloadDatas()
        
        XGL_Notice.default.addObserver(self, selector: #selector(self.loginNoticeAction), name: XGL_Notification.login.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.addBlack.notificationName, object: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
        self.reloadDatas()
    }

}

extension XGL_MessageViewController{
    func reloadDatas(){
        self.conversationDatas.removeAll()
        let infor = ChatMessageCacheManager.shared.infor
        for chat in infor.conversations.values {
            if let message = chat.last(where: {$0.messageType < 4}) {
                self.conversationDatas.append(message)
            }
        }
        self.tableView.reloadData()
    }
}

extension XGL_MessageViewController{
    @objc private func refresh(){
        self.pageIndex = 1
        
    }
    @objc private func getMore(){
        
    }
    
    @objc private func loginNoticeAction(){
        self.reloadDatas()
    }
    
    @objc private func addblackNoticeAction(notice: Notification){
        if let data = notice.object as? [String: String],let userId = data["userId"] {
            self.conversationDatas.removeFirst(where: {$0.userId == userId})
            self.tableView.reloadData()
            let infor = ChatMessageCacheManager.shared.infor
            infor.conversations.removeValue(forKey: userId)
            ChatMessageCacheManager.shared.saveInfor(inforData: infor)
        }
    }
}

extension XGL_MessageViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.conversationDatas.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 104.0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: XGL_MessageConversationTableViewCell.self)
        cell.itemData = self.conversationDatas[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.conversationDatas[indexPath.row]
        let vc = XGL_MessageChatViewController()
        vc.userId = model.userId
        vc.userName = model.name
        vc.userHead = model.header
        vc.refreshBlock = {
            self.reloadDatas()
        }
        vc.blackHandler = {
            self.conversationDatas.remove(at: indexPath.row)
            self.tableView.reloadData()
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt
        indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let model = self.conversationDatas[indexPath.row]
        let delete = UIContextualAction(style: .destructive, title: "") {
            (action, view, completionHandler) in
            let infor = ChatMessageCacheManager.shared.infor
            infor.conversations.removeValue(forKey: model.userId)
            ChatMessageCacheManager.shared.saveInfor(inforData: infor)
            self.conversationDatas.remove(at: indexPath.row)
            self.tableView.reloadData()
            completionHandler(true)
        }
        delete.image = imageWithName("icon_delete_30")
        delete.backgroundColor = UIColor.hexColor("#80FFE6").withAlphaComponent(0.2)
        
        let configuration = UISwipeActionsConfiguration(actions: [delete])
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
}

extension XGL_MessageViewController{
    private func createXglView(){
        let titleText = UILabel().then { make in
            make.text = "Message"
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 32.0)
        }
        self.tableView = UITableView().then({ make in
            make.register(cellWithClass: XGL_MessageConversationTableViewCell.self)
            make.dataSource = self
            make.delegate = self
            make.separatorStyle = .none
            make.backgroundColor = .clear
        })
//        header.setTitle("Pull down refresh", for: .idle)
//        header.setTitle("Release update", for: .pulling)
//        header.setTitle("Refresh...", for: .refreshing)
//        header.setRefreshingTarget(self, refreshingAction: #selector(self.refresh))
//        tableView.mj_header = header
//        footer.setTitle("No more data", for: .noMoreData)
//        footer.setRefreshingTarget(self, refreshingAction: #selector(self.getMore))
//        tableView.mj_footer = footer
        self.view.addSubviews([titleText,tableView])
        titleText.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.equalTo(PanNavibarH + 15.0)
        }
        self.tableView.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.bottom.equalTo(-BottomHeight)
            make.top.equalTo(titleText.snp.bottom).offset(10.0)
        }
    }
}
